import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bull';
import { CacheModule } from '@nestjs/cache-manager';
import { ThrottlerModule } from '@nestjs/throttler';
import { HttpModule } from '@nestjs/axios';
import { ConfigModule } from '@nestjs/config';

// 服务和控制器
import { ScoringController } from './scoring.controller';
import { ScoringService } from './scoring.service';
import { ScoringProcessor } from './scoring.processor';
import { AiInferenceService } from './ai-inference.service';
import { FileValidationService } from './file-validation.service';

// 数据库模块
import { DatabaseModule } from '../../database/database.module';

// 管道和守卫
import { ScoringValidationPipe } from './pipes/scoring-validation.pipe';
import { FileUploadPipe } from './pipes/file-upload.pipe';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { TaskOwnerGuard } from './guards/task-owner.guard';

// 拦截器和过滤器
import { ScoringCacheInterceptor } from './interceptors/scoring-cache.interceptor';
import { ScoringExceptionFilter } from './filters/scoring-exception.filter';

// 异常定义
import {
  ScoringException,
  FileValidationException,
  AiInferenceException,
  TaskNotFoundException,
  UnauthorizedAccessException,
} from './exceptions/scoring.exceptions';

@Module({
  imports: [
    // 核心模块
    ConfigModule,
    DatabaseModule,
    HttpModule,

    // 队列系统 - 解决隐患 #16 并发控制
    BullModule.registerQueue({
      name: 'file-processing',
      redis: {
        host: process.env.REDIS_HOST || 'localhost',
        port: parseInt(process.env.REDIS_PORT || '6379'),
        password: process.env.REDIS_PASSWORD,
        maxRetriesPerRequest: 3,
        retryDelayOnFailover: 100,
        lazyConnect: true,
        keepAlive: 30000,
      },
      defaultJobOptions: {
        removeOnComplete: 100,
        removeOnFail: 50,
        attempts: 3,
        backoff: {
          type: 'exponential',
          delay: 2000,
        },
        // 熔断器配置
        settings: {
          stalledInterval: 30 * 1000,
          maxStalledCount: 1,
        },
      },
    }),

    // 缓存系统 - 解决隐患 #6 内存泄漏
    CacheModule.register({
      store: 'redis',
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT || '6379'),
      password: process.env.REDIS_PASSWORD,
      db: parseInt(process.env.CACHE_REDIS_DB || '2'),
      ttl: 300, // 5分钟TTL
      max: 1000, // LRU最大缓存条目
      isGlobal: false, // 模块级缓存
    }),

    // HTTP限流 - 解决隐患 #16 并发控制
    ThrottlerModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: () => ({
        throttlers: [
          {
            ttl: 60000, // 1分钟
            limit: 10,  // 最多10次请求
          },
        ],
      }),
    }),
  ],
  controllers: [ScoringController],
  providers: [
    // 核心服务
    ScoringService,
    ScoringProcessor,
    AiInferenceService,
    FileValidationService,

    // 管道
    ScoringValidationPipe,
    FileUploadPipe,

    // 守卫
    JwtAuthGuard,
    TaskOwnerGuard,

    // 拦截器
    ScoringCacheInterceptor,

    // 异常过滤器
    ScoringExceptionFilter,

    // 熔断器 - 解决隐患 #3 AI服务熔断
    {
      provide: 'AI_CIRCUIT_BREAKER',
      useFactory: (configService) => {
        const CircuitBreaker = require('opossum');

        return new CircuitBreaker(
          async (imagePath: string) => {
            // AI服务调用逻辑将在AiInferenceService中实现
            throw new Error('Circuit breaker wrapper not initialized');
          },
          {
            timeout: configService.get<number>('AI_SERVICE_TIMEOUT', 10000),
            errorThresholdPercentage: configService.get<number>('AI_CIRCUIT_BREAKER_THRESHOLD', 50),
            resetTimeout: configService.get<number>('AI_CIRCUIT_BREAKER_TIMEOUT', 30000),
            rollingCountTimeout: 60000,
            rollingCountBuckets: 10,
            monitoring: true,
          }
        );
      },
      inject: ['ConfigService'],
    },

    // 异常类注册
    ScoringException,
    FileValidationException,
    AiInferenceException,
    TaskNotFoundException,
    UnauthorizedAccessException,
  ],
  exports: [
    ScoringService,
    AiInferenceService,
    FileValidationService,
  ],
})
export class ScoringModule {
  constructor() {
    // 模块初始化日志
    console.log('🔧 ScoringModule 已加载 - 零隐患MFIS规范');
  }
}